package com.cupk.controllers;

import com.cupk.dtos.CreateTaskRequest;
import com.cupk.dtos.MessageResponse;
import com.cupk.dtos.TaskDto;
import com.cupk.dtos.UpdateTaskRequest;
import com.cupk.dtos.UpdateTaskStatusRequest;
import com.cupk.services.TaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 任务管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/tasks")
@RequiredArgsConstructor
public class TaskController {

    private final TaskService taskService;

    /**
     * 获取所有任务列表
     */
    @GetMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('RESEARCHER')")
    public ResponseEntity<List<TaskDto>> getAllTasks() {
        log.info("获取所有任务列表请求");
        List<TaskDto> tasks = taskService.getAllTasks();
        return ResponseEntity.ok(tasks);
    }

    /**
     * 获取单个任务详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or @taskService.isTaskAccessible(#id, authentication.name)")
    public ResponseEntity<TaskDto> getTaskById(@PathVariable Long id) {
        log.info("获取任务详情请求，ID: {}", id);
        TaskDto task = taskService.getTaskById(id);
        return ResponseEntity.ok(task);
    }

    /**
     * 获取当前用户的任务列表
     */
    @GetMapping("/user")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<List<TaskDto>> getUserTasks(Authentication authentication) {
        String username = authentication.getName();
        log.info("获取用户任务列表请求，用户: {}", username);
        List<TaskDto> tasks = taskService.getUserTasks(username);
        return ResponseEntity.ok(tasks);
    }

    /**
     * 根据项目ID获取任务列表
     */
    @GetMapping("/project/{projectId}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('RESEARCHER')")
    public ResponseEntity<List<TaskDto>> getTasksByProject(@PathVariable Long projectId) {
        log.info("获取项目任务列表请求，项目ID: {}", projectId);
        List<TaskDto> tasks = taskService.getTasksByProject(projectId);
        return ResponseEntity.ok(tasks);
    }

    /**
     * 创建新任务
     */
    @PostMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('RESEARCHER')")
    public ResponseEntity<TaskDto> createTask(
            @Valid @RequestBody CreateTaskRequest request,
            Authentication authentication) {
        String username = authentication.getName();
        log.info("创建任务请求，用户: {}, 任务: {}", username, request.getTitle());
        TaskDto createdTask = taskService.createTask(request);
        return ResponseEntity.status(HttpStatus.CREATED).body(createdTask);
    }

    /**
     * 更新任务信息
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or @taskService.isTaskAccessible(#id, authentication.name)")
    public ResponseEntity<TaskDto> updateTask(
            @PathVariable Long id,
            @Valid @RequestBody UpdateTaskRequest request,
            Authentication authentication) {
        String username = authentication.getName();
        log.info("更新任务请求，用户: {}, 任务ID: {}", username, id);
        TaskDto updatedTask = taskService.updateTask(id, request);
        return ResponseEntity.ok(updatedTask);
    }

    /**
     * 更新任务状态
     */
    @PatchMapping("/{id}/status")
    @PreAuthorize("hasRole('ADMIN') or @taskService.isTaskAccessible(#id, authentication.name)")
    public ResponseEntity<TaskDto> updateTaskStatus(
            @PathVariable Long id,
            @Valid @RequestBody UpdateTaskStatusRequest request,
            Authentication authentication) {
        String username = authentication.getName();
        log.info("更新任务状态请求，用户: {}, 任务ID: {}, 状态: {}", username, id, request.getStatus());
        TaskDto updatedTask = taskService.updateTaskStatus(id, request.getStatus());
        return ResponseEntity.ok(updatedTask);
    }

    /**
     * 删除任务
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or @taskService.isTaskAssignee(#id, authentication.name)")
    public ResponseEntity<MessageResponse> deleteTask(
            @PathVariable Long id,
            Authentication authentication) {
        String username = authentication.getName();
        log.info("删除任务请求，用户: {}, 任务ID: {}", username, id);
        taskService.deleteTask(id);
        return ResponseEntity.ok(new MessageResponse("任务删除成功"));
    }

    /**
     * 搜索任务
     */
    @GetMapping("/search")
    @PreAuthorize("hasRole('ADMIN') or hasRole('RESEARCHER')")
    public ResponseEntity<List<TaskDto>> searchTasks(@RequestParam String keyword) {
        log.info("搜索任务请求，关键词: {}", keyword);
        List<TaskDto> tasks = taskService.searchTasks(keyword);
        return ResponseEntity.ok(tasks);
    }
}
